const Controller = require('egg').Controller

class DefaultController extends Controller {
    // async index () {
    //   const { ctx, app } = this
    //   const message = ctx.args[0]
    //   console.log(`message >> ` + message)
    //   await ctx.socket.emit('message', { name: 'robot', msg: message.msg })
    // }

    async ping() {
        const message = this.ctx.args[0]
        await this.ctx.socket.emit('res', `server >> Hi! I've got your message: ${message}`)

        const { app, socket, logger, helper } = this.ctx
        const id = socket.id

        //连接命名空间
        const nsp = app.io.of('/')

        // 根据id给指定连接发送消息

        if (id) {
            nsp.sockets.forEach((item, key) => {
                if (id === key) {
                    console.log(`item => ` + key)
                    item.emit('res', "server >> hello " + key)
                }
            })


            if (nsp.sockets[id]) {
                console.log(`sockets[id] >> ${id}`)
                nsp.sockets[id].emit('res', "server >> hello " + id)
                socket.to(id).emit('res', "server >> hello " + id)
            } else {
                console.log(`sockets[id] >> ${id} >> not found emit`)
                console.log(nsp.sockets[id])
            }

            // let counter = 0
            // setInterval(() => {
            //     if (nsp.sockets[id]) {
            //       console.log(`sockets[id] >> ${id}`)
            //       nsp.sockets[id].emit('res', "hello " + counter++)
            //     } else {
            //       console.log(`sockets[id] >> ${id} >> not found emit`)
            //     }
            // }, 2000)
        }

        //接收客户端发送来的信息
        this.ctx.socket.on('hey', msg => {
            console.log('server >> hey', msg)
            //this.ctx.emit('res', "来自 client 信息：" + msg)
        })
    }

    async disconnect() {
        const message = this.ctx.args[0]
        console.log('server >> disconnect')
        console.log(message)
    }
}

module.exports = DefaultController